<template>
  <div id="UploadA">
    <div class="drawer-adjustment">
      <div class="fb-title">
        <i class="el-icon-s-promotion"></i>
        <span>发布商品</span>
      </div>
      <el-row type="flex" justify="center" align="middle">
        <el-col :span="20">
          <el-form :model="form" class="form-adjustment" label-position="top" id="form-box">
            <el-row>
              <el-col :span="11">
                <el-form-item label="商品名称">
                  <el-input v-model="form.goodName" autocomplete="off" placeholder="请输入商品名称"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="11" :offset="2">
                <el-form-item label="商品价格">
                  <el-input v-model="form.goodPrice" autocomplete="off" placeholder="请输入商品价格"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="11">
                <el-form-item label="商品种类" id="cascader">
                  <el-cascader :props="type" v-model="form.class" style="width: 100%"></el-cascader>
                </el-form-item>
              </el-col>
              <el-col :span="11" :offset="2">
                <el-form-item label="库存">
                  <el-input v-model="form.stock" placeholder="请输入库存"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="11">
                <el-form-item label="富文本编辑">
                  <div id="editor"></div>
                </el-form-item>
              </el-col>
              <el-col :span="11" :offset="2">
                <el-form-item label="上传附件">
                  <el-upload
                    id="img-upload"
                    action=""
                    ref="upload"
                    :auto-upload="false"
                    :file-list="form.medias"
                    list-type="picture"
                    multiple
                    :on-remove="handleRemoveHigh"
                    :before-remove="beforeRemove"
                    :on-change="handleChangeHigh"
                    accept="*"
                    style="position: relative;"
                  >
                    <el-row>
                      <el-button class="submit-button">上传附件</el-button>
                      <div style="color: #7D7D7D">图片不能大于12m，类型只能是jpg、png、mp4</div>
                    </el-row>
                  </el-upload>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <el-row type="flex" align="middle" justify="center">
            <el-col :span="24">
              <el-button class="good-submit" v-on:click="goodSubmit">发布商品</el-button>
            </el-col>
          </el-row>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import E from 'wangeditor';
export default {
  name: "UploadA",
  data() {
    return {
      editor:null,
      msg:"",
      form: {
        goodName: null,
        goodPrice: null,
        description: null,
        goodPicture: null,
        stock: null,
        class: null,
        medias: null
      },
      drawer: false,
      type: {
        lazy: true,
        lazyLoad: this.lazyLoad
      },
    }
  },
  props: {
    value: '',
  },
  mounted() {
    this.initEditor();
  },
  methods: {
    //upload改变时的钩子
    handleChangeHigh: function (file, fileList) {
      if (this.handleBeforeUpload(file)) {
        this.form.medias = fileList;
        // alert(JSON.stringify(this.form.medias))
        // console.log("high:", this.form.medias);
      }
    },
    // handleChangeSmall: function (file, fileList) {
    //   this.form.smallPicture = fileList;
    //   console.log("small:", this.form.smallPicture)
    // },
    handleRemoveHigh(file, fileList) {
      for (var i = 0; i < this.form.medias.length; i ++) {
        if (this.form.medias[i].name === file.name) {
          delete this.form.medias[i];
          break;
        }
      }
    },
    handleBeforeUpload: function (file) {
      var testmsg = file.name.substring(file.name.lastIndexOf('.')+1)
      const extension = testmsg === 'jpg';
      const extension2 = testmsg === 'png';
      const extension3 = testmsg === 'mp4';
      const isLt2M = file.size / 1024 / 1024  < 12;
      if(!extension  && !extension2 && !extension3) {
        this.$message({
          message: '上传文件只能是 jpg, png, mp4格式!',
          type: 'warning'
        });
      }
      if(!isLt2M) {
        this.$message({
          message: '上传文件大小不能超过 12MB!',
          type: 'warning'
        });
      }
      return (extension || extension2 || extension3) && isLt2M;
    },
    handleRemoveSmall(file) {
      for (var i = 0; i < this.form.medias.length; i ++) {
        if (this.form.medias[i].name === file.name) {
          delete this.form.medias[i];
          break;
        }
      }
    },
    beforeRemove(file, fileList) {
      // return this.$confirm(`确定移除 ${ file.name }？`);
    },
    lazyLoad(node, resolve) {
      setTimeout(() => {
        let nodes = [];
        let level = node.level;
        if (level === 0) {
          this.$api.good.getParentClass().then(res => {
            if (res.data.code === 200) {
              console.log("1级目录", res);
              // nodes = Array.from(res.data.data).map(item => ({
              //   value: item.classId,
              //   label: item.className,
              //   leaf: false
              // }))
              res.data.data.forEach(item => {
                nodes.push({
                  value: item.classId,
                  label: item.className,
                  leaf: false,
                })
              })
              resolve(nodes)
              console.log("nodes", nodes)
            }
          })
        } else {
          this.$api.good.getChildClass({
            classId: node.value
          }).then(res => {
            if (res.data.code === 200) {
              res.data.data.forEach(item => {
                nodes.push({
                  value: item.classId,
                  label: item.className,
                  leaf: true
                })
              })
              resolve(nodes)
            }
          })
        }
        // nodes = [{'value': 1, 'label': 1, leaf: true}, {'value': 2, 'label': 2, leaf: true}]

      }, 1000)
    },
    initEditor(){
      this.editor = new E('#editor');
      this.editor.config.menus = [
        'head', // 标题
        'bold', // 粗体
        'fontSize', // 字号
        'fontName', // 字体
        'italic', // 斜体
        'underline', // 下划线
        'strikeThrough', // 删除线
        'foreColor', // 文字颜色
        'backColor', // 背景颜色
        'link', // 插入链接
        'list', // 列表
        'justify', // 对齐方式
        'quote', // 引用
        'emoticon', // 表情
        'image', // 插入图片
        'table', // 表格
        'video', // 插入视频
        'code', // 插入代码
        'undo', // 撤销
        'redo', // 重复
        'fullscreen' // 全屏
      ];
      this.editor.config.onchange = html => {
        this.$emit('input', html);
      };
      this.editor.config.uploadImgServer = 'http://121.196.200.212:8081/seller/uploadDescriptionImage';
      this.editor.config.uploadImgMaxSize = 10 * 1024 * 1024; // 将图片大小限制为 10M
      this.editor.config.uploadFileName = 'descriptionImage'; //后端接受上传文件的参数名
      this.editor.config.uploadImgMaxLength = 1; // 限制一次最多上传 1 张图片
      this.editor.config.showLinkImg = false; //隐藏网络图片上传
      this.editor.config.uploadImgHeaders={
        Authorization: sessionStorage.getItem("token")
      }
      this.editor.config.uploadVideoHeaders={
        Authorization: sessionStorage.getItem("token")
      }
      this.editor.config.uploadImgHooks = {
        fail: (xhr, editor, result) => {
          // 插入图片失败回调
          console.log(result);
        },
        success: (xhr, editor, result) => {
          // 图片上传成功回调
          console.log(result);
        },
        timeout: (xhr, editor) => {
          // 网络超时的回调
          console.log('网络超时');
        },
        error: (xhr, editor) => {
          // 图片上传错误的回调
          console.log('上传错误');
        },
        //回显
        customInsert: (insertImg, result, editor) => {
          let url=result.url
          insertImg(url[0]);
        },
      };
      this.editor.config.uploadVideoServer = 'http://121.196.200.212:8081/seller/uploadDescriptionVideo';
      this.editor.config.uploadVideoMaxSize = 5000*1024*1024;
      this.editor.config.uploadVideoName ="descriptionVideo";
      this.editor.config.uploadVideoMaxLength=1;
      this.editor.config.showLinkVideo=false;
      this.editor.config.uploadVideoHooks = {
        fail: (xhr, editor, result) => {
          // 插入图片失败回调
          console.log(result);
        },
        success: (xhr, editor, result) => {
          // 图片上传成功回调
          console.log(result);
        },
        timeout: (xhr, editor) => {
          // 网络超时的回调
          console.log('网络超时');
        },
        error: (xhr, editor) => {
          // 图片上传错误的回调
          console.log('上传错误');
        },
        //回显
        customInsert: (insertVideoFn, result, editor) => {
          let url=result.url
          insertVideoFn(url[0]);
        },
      };
      this.editor.config.height=200;

      this.editor.create();
      this.editor.txt.html(this.value);
    },
    goodSubmit: function () {
      this.form.description = this.editor.txt.html();
      let fd = new FormData();
      fd.append('_method','post');
      if (this.form.medias != null) {
        this.form.medias.forEach(item => {
          fd.append("medias",item.raw);
        });
        fd.append("goodName", this.form.goodName);
        fd.append("price", this.form.goodPrice);
        fd.append("description", this.form.description);
        fd.append("parentClassId", this.form.class[0]);
        fd.append("childClassId", this.form.class[1]);
        fd.append("stock", this.form.stock);
      }
      this.releaseGood(fd);
    },
    releaseGood: function (fd) {
      const loading = this.$loading({
        lock: true,
        text: "删除作品图片中",
        spinner: "el-icon-loading",
        background: "rgba(255, 255, 255, 0.8)",
        target: "#UploadA",
        customClass: "loading-customClass"
      });
      this.$api.seller.releaseGood(fd).then(res => {
        console.log("releaseGood", res);
        if (res.data.code === 200) {
          this.$message({
            message: "上传成功",
            type: "success"
          });
          this.formDataInit();
          this.clearUploadedImage();
          loading.close();
        }
        loading.close();
      })
    },
    //清除文件列表
    clearUploadedImage: function () {
      this.$refs['upload'].clearFiles();
    },
    formDataInit: function () {
      this.form =  {
        goodName: null,
        goodPrice: null,
        description: null,
        goodPicture: null,
        stock: null,
        class: null,
        medias: null
      };

    }
  }
}
</script>

<style lang="scss" scoped>
#UploadA {
  margin-top: -70px;
  border-radius: 25px;
}
#editor {
  width: 100%;
  height: 500px;
  max-height: 500px;
}
.drawer-adjustment {
  border-radius: 25px;
}
#cascader {
  >>> .el-cascader-node.in-active-path {
    color: rgba(176, 224, 230, 1);
  }
}
#form-box {
  >>> .el-textarea__inner {
    font-size: 24px;
    resize: none;
    border: 2px solid #C0C4CC;
  }
  >>> .el-textarea__inner::placeholder {
    font-size: 24px;
    color: #C0C4CC;
  }
  >>> .el-textarea__inner:focus {
    border: 2px solid rgba(176, 224, 230, 1);
  }
  #editor{
    width: 65%;
    height: 65%;
  }
}
.left {
  position: fixed;
  width: 15%;
  height: 100%;
  top: 10%;
}
.row-height {
  /*width: 1000px;*/
  /*height: 400px;*/
}
.table-size {
  width: 100%;
}
.top {
  position: fixed;
  width: 100%;
  height: 10%;
  vertical-align: middle;
  background: rgba(176, 224, 230, 1);
}
.middle {
  position: relative;
  top: 18%;
  left: 18%;
  width: 70%;
  height: 100%;
  vertical-align: middle;
}
.adjustment-pag {
  float: right;
  padding-top: 30px;
}
#add {
  border: 2px dashed grey;
  border-radius: 10px;
  width: 250px;
  height: 300px;
  font-size: 90px;
  color: grey;
  position: relative;
  text-align: center;
  display: inline-block;
}
#add:hover {
  border: 2px dashed steelblue;
  color: steelblue;
  cursor: pointer;
}
.fb-textarea {
  background: white;
  border: 2px dashed #99eab7;
  width: 70px;
  height: 100%;
  position: fixed;
  right: 0;
}
.add-img {
  width: 50px;
  height: 50px;
}
.fb-textarea-adjustment {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translateY(-50%) translateX(-50%);
}
.fb-title {
  font-weight: bold;
  font-size: 36px;
  height: 60px;
  color: rgba(28, 28, 28, 0.6);
  padding-left: 30px;
  //background: rgba(176, 224, 230, 1);
  padding-top: 30px;
  border-radius: 25px 25px 0 0;
}
.drawer-adjustment {
  //padding-top: 100px;
}
.form-adjustment {
  padding-top: 30px;
}
.submit-button {
  background: rgba(176, 224, 230, 1);
  color: rgba(28, 28, 28, 0.6);
  font-size: 20px;
  width: 100%;
}
.submit-button:hover {
  background: rgba(176, 224, 230, 0.6);
}
.good-submit {
  width: 100%;
  background: rgba(176, 224, 230, 1);
  color: rgba(28, 28, 28, 0.6);
  font-size: 20px;
}
.good-submit:hover {
  background: rgba(176, 224, 230, 0.6);
}
>>> .el-input__inner {
  border-width: 2px;
}
>>> .el-col-6 {
  height: 330px;
}
>>> .el-menu-item.is-active {
  color: rgba(176, 224, 230, 1);
}
>>> .el-input__inner:hover {
  border-color: rgba(176, 224, 230, 1);
}
>>> .el-cascader .el-input .el-input__inner:focus, .el-cascader .el-input.is-focus .el-input__inner {
  border-color: rgba(176, 224, 230, 1);
}
>>>.el-form-item__label {
  font-size: 24px;
  font-weight: 500;
  color: #7D7D7D;
}
>>>.el-upload-list {
  max-height: 210px;
  overflow: auto;
}
</style>
